package com.vf.admin.client.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.vf.admin.client.common.RedisKeys;
import com.vf.admin.client.dao.AppOrderDao;
import com.vf.admin.client.dao.AlipayConfigsDao;
import com.vf.admin.client.result.PayInfoResult;
import com.vf.admin.client.service.AlipayConfigsService;
import com.vf.admin.client.service.AppOrderService;
import com.vf.admin.client.service.VipOrderService;
import com.vf.admin.client.service.pay.AppPaySetupLoadBalancer;
import com.vf.admin.common.Constants;
import com.vf.admin.miaodong.entity.*;
import com.vf.admin.common.redis.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Random;

import static com.vf.admin.utils.RandomUtil.getOrderIdByUUId;

/**
 * 系统配置
 */
@Service
public class AlipayConfigsServiceImpl implements AlipayConfigsService {

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private AlipayConfigsDao alipayConfigsDao;
    //钱包订单
    @Autowired
    private AppOrderService appOrderService;
    //vip订单
    @Autowired
    private VipOrderService vipOrderService;

    /**
     * 支付宝支付宝预下单   废弃
     *
     * @param user 充值用户
     * @return
     */
    @Override
    public String otherAlipayWeb(AppUser user, AppCzMoney czMoney) {
        //添加订单记录
        AppOrder appOrder = new AppOrder();
        appOrder.setCreatetime(new Date());
        appOrder.setOrdernum(getOrderIdByUUId());//生成订单号
        appOrder.setCzMoneyId(czMoney.getId());
        appOrder.setMoney(new BigDecimal(czMoney.getMoney()));
        appOrder.setStatus(Constants.dingdan_status_dfk);//默认 1、代付款 2、已付款
        appOrder.setType(Constants.dingdan_zhiFuLeiXing_zfb); //订单支付类型  默认 1、支付宝 2、微信 3、苹果
        appOrder.setUserid(user.getId());//下单人信息
        appOrder.setPic(user.getPic());
        appOrder.setNick(user.getNick());
        appOrder.setPhone(user.getLoginname());
        appOrder.setNum(czMoney.getDiamonds().add(czMoney.getGive()));
        appOrderService.save(appOrder);

        //***************** 支付宝预处理 **********************
        AlipayTradeWapPayModel model = new AlipayTradeWapPayModel(); //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式
        model.setBody("充值");//对一笔交易的具体描述信息。如果是多种商品，请将商品描述字符串累加传给body。
        model.setSubject("钻石充值");//商品名称
        model.setOutTradeNo(appOrder.getOrdernum()); //商户订单号(自动生成)
//        model.setTotalAmount(new BigDecimal(czMoney.getMoney()).setScale(2, BigDecimal.ROUND_HALF_UP).stripTrailingZeros().toPlainString());//支付金额
        model.setTotalAmount("0.01");
        model.setProductCode("QUICK_WAP_PAY");//销售产品码（固定值）

        //权重的方法
        AlipayConfigs randomConfig = getWeightPlayInfo();

        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeWapPayRequest webRequest = new AlipayTradeWapPayRequest();
        webRequest.setBizModel(model);
        webRequest.setNotifyUrl(randomConfig.getNotifyUrl() + "/" + randomConfig.getAppId());//异步回调地址（后台）  拼接appId
        webRequest.setReturnUrl(randomConfig.getReturnUrl());

        //返回支付宝订单信息(预处理)
        AlipayClient alipayClient = new DefaultAlipayClient(
                randomConfig.getGateWayUrl(),
                randomConfig.getAppId(),
                randomConfig.getAppPrivateKey(),
                randomConfig.getFormat(),
                randomConfig.getCharset(),
                randomConfig.getAlipayPublicKey(),
                randomConfig.getSignType()
        );

        String orderString = "";
        try {
            orderString = alipayClient.pageExecute(webRequest, "get").getBody();
        } catch (Exception e) {
            return orderString;
        }
        return orderString;
    }

    /**
     * 查找当前可用的支付信息
     * 通过权重来分配当前用那个支付。权重为概率值。总概率为100
     *
     * @return
     */
    public AlipayConfigs getWeightPlayInfo() {
        List<AlipayConfigs> alipayConfigs = null;
        if (!redisUtil.hasKey(RedisKeys.ALICONFIGS)) {
            alipayConfigs = alipayConfigsDao.list();
            redisUtil.set(RedisKeys.ALICONFIGS, alipayConfigs, RedisKeys.ALICONFIGSOUTTIME);
        } else {
            alipayConfigs = (List<AlipayConfigs>) redisUtil.get(RedisKeys.ALICONFIGS);
        }
        Integer sumWeight = 0;//总权重的值
        JSONArray as = new JSONArray();//存入对象用于概率
        Integer index = 0;
        for (int i = 0; i < alipayConfigs.size(); i++) {
            Integer weight = alipayConfigs.get(i).getWeight();
            if (weight > 0) {
                sumWeight = sumWeight + weight;
                for (int j = 0; j < weight; j++) {
                    as.add(index, alipayConfigs.get(i));
                    index++;//放后面保证0也有值
                }
            }
        }
        Integer r = new Random().nextInt(sumWeight + 1);//随机数生成概率
        AlipayConfigs alipayConfigs1 = (AlipayConfigs) as.get(r);
        System.out.println("权重：" + alipayConfigs1);
        return (AlipayConfigs) as.get(r);
    }

    @Override
    public AlipayConfigs getAppIdInfo(String appIdStr) {
        return alipayConfigsDao.getAppIdInfo(appIdStr);
    }

    @Override
    public PayInfoResult aliPayDiamondTransactionsH5(AppUser user, AppCzMoney czMoney,String mobileSpec) {
        //权重的方法
        AlipayConfigs randomConfig = getWeightPlayInfo();
        //添加订单记录
        AppOrder appOrder = new AppOrder();
        appOrder.setCreatetime(new Date());
        appOrder.setOrdernum(getOrderIdByUUId());//生成订单号
        appOrder.setCzMoneyId(czMoney.getId());
        appOrder.setMoney(new BigDecimal(czMoney.getMoney()));
        appOrder.setStatus(Constants.dingdan_status_dfk);//默认 1、代付款 2、已付款
        appOrder.setType(Constants.dingdan_zhiFuLeiXing_zfb); //订单支付类型  默认 1、支付宝 2、微信 3、苹果  4、杉德支付宝 5、杉德微信
        appOrder.setUserid(user.getId());//下单人信息
        appOrder.setPic(user.getPic());
        appOrder.setNick(user.getNick());
        appOrder.setPhone(user.getLoginname());
        appOrder.setNum(czMoney.getDiamonds().add(czMoney.getGive()));
        appOrder.setMobileSpec(mobileSpec);
        appOrderService.save(appOrder);
        //***************** 支付宝预处理 **********************
        AlipayTradeWapPayModel model = new AlipayTradeWapPayModel(); //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式
        model.setBody("充值");//对一笔交易的具体描述信息。如果是多种商品，请将商品描述字符串累加传给body。
        model.setSubject("钻石充值");//商品名称
        model.setOutTradeNo(appOrder.getOrdernum()); //商户订单号(自动生成)
        model.setTotalAmount(new BigDecimal(czMoney.getMoney()).setScale(2, BigDecimal.ROUND_HALF_UP).stripTrailingZeros().toPlainString());//支付金额
//        model.setTotalAmount("0.01");
        model.setProductCode("QUICK_WAP_PAY");//销售产品码（固定值）
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeWapPayRequest webRequest = new AlipayTradeWapPayRequest();
        webRequest.setBizModel(model);
        webRequest.setNotifyUrl(randomConfig.getNotifyUrl() + "/" + randomConfig.getAppId());//异步回调地址（后台）  拼接appId
        webRequest.setReturnUrl(randomConfig.getReturnUrl());
        //返回支付宝订单信息(预处理)
        AlipayClient alipayClient = new DefaultAlipayClient(
                randomConfig.getGateWayUrl(),
                randomConfig.getAppId(),
                randomConfig.getAppPrivateKey(),
                randomConfig.getFormat(),
                randomConfig.getCharset(),
                randomConfig.getAlipayPublicKey(),
                randomConfig.getSignType()
        );
        PayInfoResult payInfoResult = new PayInfoResult();
        String orderString = "";
        try {
            orderString = alipayClient.pageExecute(webRequest, "get").getBody();
            payInfoResult.setOrderNo(appOrder.getOrdernum());
            payInfoResult.setPayUrl(orderString);
        } catch (Exception e) {
            return payInfoResult;
        }
        return payInfoResult;
    }

    @Override
    public PayInfoResult aliPayOpenVipTransactionsH5(AppUser user, VipPackage vipPackage,String mobileSpec) {
        //权重的方法
        AlipayConfigs randomConfig = getWeightPlayInfo();
        //添加订单记录
        VipOrder vipOrder = new VipOrder();
        vipOrder.setUserId(user.getId());
        vipOrder.setOrderNo(getOrderIdByUUId());//订单号
        vipOrder.setVipPackageId(vipPackage.getId());
        vipOrder.setStatus(0);  //0待支付 1已支付
        vipOrder.setPayType("alipay");
        vipOrder.setCreateTime(new Date());
        vipOrder.setType(Constants.dingdan_zhiFuLeiXing_zfb); //订单支付类型  默认 1、支付宝 2、微信 3、苹果  4、杉德支付宝 5、杉德微信
        vipOrder.setMobileSpec(mobileSpec);
        vipOrder.setNick(user.getNick());
        vipOrder.setPhone(user.getLoginname());
        vipOrder.setPrice(vipPackage.getPrice());
        vipOrder.setPic(user.getPic());
        vipOrderService.save(vipOrder);
        //***************** 支付宝预处理 **********************
        AlipayTradeWapPayModel model = new AlipayTradeWapPayModel(); //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式
        model.setBody("开通贵族");//对一笔交易的具体描述信息。如果是多种商品，请将商品描述字符串累加传给body。
        model.setSubject("会员充值");//商品名称
        model.setOutTradeNo(vipOrder.getOrderNo()); //商户订单号(自动生成)
        model.setTotalAmount(vipPackage.getPrice().setScale(2, BigDecimal.ROUND_HALF_UP).stripTrailingZeros().toPlainString());//支付金额
//        model.setTotalAmount("0.01");
        model.setProductCode("QUICK_WAP_PAY");//销售产品码（固定值）
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeWapPayRequest webRequest = new AlipayTradeWapPayRequest();
        webRequest.setBizModel(model);
        webRequest.setNotifyUrl(randomConfig.getVipNotifyUrl() + "/" + randomConfig.getAppId());//异步回调地址（后台）  拼接appId
        webRequest.setReturnUrl(randomConfig.getReturnUrl());
        //返回支付宝订单信息(预处理)
        AlipayClient alipayClient = new DefaultAlipayClient(
                randomConfig.getGateWayUrl(),
                randomConfig.getAppId(),
                randomConfig.getAppPrivateKey(),
                randomConfig.getFormat(),
                randomConfig.getCharset(),
                randomConfig.getAlipayPublicKey(),
                randomConfig.getSignType()
        );
        PayInfoResult payInfoResult = new PayInfoResult();
        String orderString = "";
        try {
            orderString = alipayClient.pageExecute(webRequest, "get").getBody();
            payInfoResult.setOrderNo(vipOrder.getOrderNo());
            payInfoResult.setPayUrl(orderString);
        } catch (Exception e) {
            return payInfoResult;
        }
        return payInfoResult;
    }

    @Override
    public PayInfoResult shopH5(String name,BigDecimal price) {
        //权重的方法
        AlipayConfigs randomConfig = getWeightPlayInfo();
        //添加订单记录
        //***************** 支付宝预处理 **********************
        AlipayTradeWapPayModel model = new AlipayTradeWapPayModel(); //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式
        model.setBody("开通贵族");//对一笔交易的具体描述信息。如果是多种商品，请将商品描述字符串累加传给body。
        model.setSubject("会员充值");//商品名称
        model.setOutTradeNo(getOrderIdByUUId()); //商户订单号(自动生成)
        model.setTotalAmount(price.setScale(2, BigDecimal.ROUND_HALF_UP).stripTrailingZeros().toPlainString());//支付金额
//        model.setTotalAmount("0.01");
        model.setProductCode("QUICK_WAP_PAY");//销售产品码（固定值）
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeWapPayRequest webRequest = new AlipayTradeWapPayRequest();
        webRequest.setBizModel(model);
        webRequest.setNotifyUrl(randomConfig.getVipNotifyUrl() + "/" + randomConfig.getAppId());//异步回调地址（后台）  拼接appId
        webRequest.setReturnUrl(randomConfig.getReturnUrl());
        //返回支付宝订单信息(预处理)
        AlipayClient alipayClient = new DefaultAlipayClient(
                randomConfig.getGateWayUrl(),
                randomConfig.getAppId(),
                randomConfig.getAppPrivateKey(),
                randomConfig.getFormat(),
                randomConfig.getCharset(),
                randomConfig.getAlipayPublicKey(),
                randomConfig.getSignType()
        );
        PayInfoResult payInfoResult = new PayInfoResult();
        String orderString = "";
        try {
            orderString = alipayClient.pageExecute(webRequest, "get").getBody();
            payInfoResult.setOrderNo(model.getOutTradeNo());
            payInfoResult.setPayUrl(orderString);
        } catch (Exception e) {
            return payInfoResult;
        }
        return payInfoResult;
    }

}
